package cn.cheneyjoo.service.impl;

import cn.cheneyjoo.Model.OrderDetail;
import cn.cheneyjoo.Model.OrderMain;
import cn.cheneyjoo.mapper.OrderDetailMapper;
import cn.cheneyjoo.mapper.OrderMainMapper;
import cn.cheneyjoo.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Order;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMainMapper orderMainMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 因为涉及到主子表数据插入，所以需要开启事务
     * 如果需要捕获异常信息作为日志记录就需要设置手动回滚
     *  TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
     * @param orderMain 订单信息
     * @return
     */
    @Transactional
    @Override
    public boolean saveOrder(OrderMain orderMain) {
        orderMain.setCreateTime(new Date());
        orderMain.setUpdateTime(new Date());
        orderMainMapper.insert(orderMain);
        List<OrderDetail> orderDetails=orderMain.getOrderDetails();
        for (OrderDetail orderDetail : orderDetails) {
            orderDetail.setCreateTime(new Date());
            orderDetail.setUpdateTime(new Date());
            orderDetail.setOrderId(orderMain.getId());
            orderDetailMapper.insert(orderDetail);
        }
        return true;
    }

    /**
     * 分页查询
     * @param pageIndex 页码
     * @param pageSize 每页条数
     * @param where 查询条件：订单创建时间范围、订单状态（未支付、已支付、已失效、已删除）
     * @return
     */
    @Override
    public List<OrderMain> getOrdersByPage(int pageIndex, int pageSize, Map<String, String> where) {
        Page<OrderMain> orderIPage = new Page<>(pageIndex, pageSize);
        QueryWrapper<OrderMain> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            if (where.containsKey("StartTime") && Optional.of(where.get("StartTime")).isPresent()) {
                queryWrapper.ge("create_time" ,simpleDateFormat.parse(where.get("StartTime")));
            }
            if (where.containsKey("EndTime") && Optional.of(where.get("EndTime")).isPresent()) {
                queryWrapper.le("create_time", simpleDateFormat.parse(where.get("EndTime")));
            }
        }catch (ParseException ex){
            ex.printStackTrace();
            return null;
        }
        if (where.containsKey("OrderStatus") && Optional.of(where.get("OrderStatus")).isPresent()) {
            queryWrapper.eq("order_status", Integer.parseInt(where.get("OrderStatus")));
        }
        orderIPage = orderMainMapper.selectPage(orderIPage, queryWrapper);
        List<OrderMain> records = orderIPage.getRecords();
        for (var item:records) {
            Integer id =item.getId();
            item.setOrderDetails(getOrderDetailByOrderId(id));
        }
        return records;
    }

    /**
     * 根据订单ID查询订单明细表详情
     * @param orderId
     * @return
     */
    @Override
    public List<OrderDetail> getOrderDetailByOrderId(int orderId) {
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id",orderId));
        return orderDetailList;
    }
}
